package com.cfpamf.ms.insur.pay.integration.wxpay;

import com.cfpamf.common.ms.exception.MSException;
import com.cfpamf.ms.insur.pay.config.WxPayProperties;
import com.cfpamf.ms.insur.pay.constant.BizExceptEnum;
import com.cfpamf.ms.insur.wx.client.WechatPayClient;
import org.springframework.util.Assert;

import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Create By zhengjing on 2019-10-17 10:55
 */
public class WxClientManager {

    @NotNull
    private Map<String, WechatPayClient> clientMap;

    @NotNull
    private WechatPayClient primaryClient;

    @NotNull
    private Map<String, WxPayProperties> propertiesMap;

    @NotNull
    private WxPayProperties primaryProperties;

    public WxClientManager(Map<String, WechatPayClient> clientMap, WechatPayClient primaryClient) {

        Assert.notNull(clientMap, "微信支付客户端不能为空");
        Assert.notNull(primaryClient, "微信支付主客户端不能为空");
        this.clientMap = clientMap;
        if (!(this.clientMap instanceof ConcurrentHashMap)) {
            this.clientMap = Collections.synchronizedMap(this.clientMap);
        }
        this.primaryClient = primaryClient;
    }

    public WxClientManager(Map<String, WechatPayClient> clientMap, WechatPayClient primaryClient,
                           Map<String, WxPayProperties> propertiesMap, WxPayProperties primaryProperties) {
        Assert.notNull(clientMap, "微信支付客户端不能为空");
        Assert.notNull(primaryClient, "微信支付主客户端不能为空");
        Assert.notNull(propertiesMap, "微信支付配置不能为空");
        Assert.notNull(primaryProperties, "微信支付主配置不能为空");
        this.clientMap = clientMap;
        if (!(this.clientMap instanceof ConcurrentHashMap)) {
            this.clientMap = Collections.synchronizedMap(this.clientMap);
        }
        this.primaryClient = primaryClient;
        this.propertiesMap = propertiesMap;

        if (!(this.propertiesMap instanceof ConcurrentHashMap)) {
            this.propertiesMap = Collections.synchronizedMap(this.propertiesMap);
        }
        this.primaryProperties = primaryProperties;
    }

    public WechatPayClient getClientBySystemCode(String systemCode) {
        WechatPayClient client = clientMap.get(systemCode);
        if (client == null) {
            throw new MSException(BizExceptEnum.SYSTEM_CONFIG_ERROR);
        }
        return client;
    }

    public WechatPayClient getPrimaryClient() {
        return primaryClient;
    }

    public WxPayProperties getPropertiesBySystemCode(String systemCode) {
        WxPayProperties properties = propertiesMap.get(systemCode);
        if (properties == null) {
            throw new MSException(BizExceptEnum.SYSTEM_CONFIG_ERROR);
        }
        return properties;
    }

    public WxPayProperties getPrimaryProperties() {
        return primaryProperties;
    }

}
